package com.squirrels.server.work;

import com.squirrels.server.annotation.NettyServerWorker;
import com.squirrels.server.common.constant.RoomConstant;
import com.squirrels.server.common.constant.SystemConstant;
import com.squirrels.server.common.constant.UserConstant;
import com.squirrels.server.entity.Room;
import com.squirrels.server.message.protobuf.Message;
import com.squirrels.server.service.RoomService;
import com.squirrels.server.service.UserDataService;
import com.squirrels.server.utils.JWTUtils;
import dev.morphia.Datastore;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

/**
 * 创建者: FlyingSquirrels
 * 创建时间: 2024/8/21 17:33
 * 描述: 房间控制类
 */
@Slf4j
@NettyServerWorker("room")
public class RoomWorker extends ServerWorker{

    private static UserDataService dataService;
    private static RoomService roomService;

    /**
     * 为当前类注入service
     * @param datastore
     */
    private void doService(Datastore datastore) {
        dataService = UserDataService.operation(datastore);
    }

    @Override
    public Message.Entity doWorker(String operationBase) {
        // 未登录, 响应错误信息
        if (!JWTUtils.jwtUtils.checkToken(entity.getToken())) {
            return errorMsg(UserConstant.USER_NOT_LOGIN,entity);
        }
        // 注入 Service
        doService(datastore);
        roomService = RoomService.getService();
        Message.Entity responseData;
        // 根据请求头部执行操作
        switch (operationBase){
            // 加入房间 没有房间就创建房间
            case "joinRoom" -> {
                responseData = joinRoom(entity);
            }
            // 退出房间
            case "exitRoom" ->{
                responseData = exitRoom(entity);
            }
            case "operation" -> {
                responseData = operation(entity);
            }
            default -> {
                responseData = errorMsg(UserConstant.OPERATION_NOT_ERROR,entity);
            }
        }
        return responseData;
    }

    // 用户操作
    private Message.Entity operation(Message.Entity entity) {
        Room room = roomService.getRoomUserById(entity.getPlayer().getRoom());
        room.update(entity.getPlayer().getId(),ctx,entity);
        return null;
    }

    // 退出房间
    private Message.Entity exitRoom(Message.Entity entity) {
        String room = entity.getPlayer().getRoom();
        Room currentRoom = roomService.getRoomUserById(room);
        // 房间不存在 已经退出
        if (null == currentRoom){
            return msg(SystemConstant.OK,entity);
        }
        // 用户退出
        if(!currentRoom.exitUser(entity,ctx)){
            // 用户不在该房间
            return errorMsg(SystemConstant.SERVER_ERROR,entity);
        }
        // 用户退出
        return msg(SystemConstant.OK,entity);

    }

    // 加入房间
    private Message.Entity joinRoom(Message.Entity entity) {
        Message.Player player = entity.getPlayer();
        String room = player.getRoom();
        String roomId;
        // 没有房间就创建房间
        if (StringUtils.hasText(room)){
            Room currentRoom = roomService.getRoomUserById((room));
            // 房间不存在
            if (null == currentRoom){
               return errorMsg(RoomConstant.ROOM_NOT_EXISTS,entity);
            }
            // 加入房间失败
            if (currentRoom.addRoom(player.getId(),sender,player.getName())){
               return errorMsg(RoomConstant.ROOM_NOT_EXISTS,entity);
            }
            roomId = currentRoom.getId();
        }else{
            // 查找空闲房间
            String notFullRoomId = roomService.getNotFullRoomId();
            // 存在未满的房间
            if (StringUtils.hasText(notFullRoomId)){
                Room aimRoom = roomService.getRoomUserById(notFullRoomId);
                if (null == aimRoom){
                    return errorMsg(RoomConstant.ROOM_NOT_EXISTS,entity);
                }
                aimRoom.addRoom(player.getId(),sender,player.getName());
                // 加入成功
                roomId = aimRoom.getId();
            }else {
                // 没有房间创建房间
                roomId = roomService.CreateRoom(player.getId(),sender,player.getName());
            }
        }
        // 返回加入的房间id
        return Message.Entity.newBuilder()
                .setOperation(entity.getOperation())
                .setOperationBase(entity.getOperationBase())
                .setCode((int)SystemConstant.OK.getValue())
                .setDataType(Message.Entity.EntityType.DataType)
                .setData(Message.Data.newBuilder().setInfo(roomId).build())
                .build();
    }
}
